# -*- coding: utf-8 -*-

import cv
import cv2
import numpy as np

def kmeans():
    img=cv.LoadImage('D:/test/pic/n_21644267146509.jpg')
    cv.NamedWindow('原始图像',1)
    cv.ShowImage('原始图像',img)
    cv.WaitKey(0)
    
    #样本
    samples = cv.CreateMat(img.width*img.height, 1, cv.CV_32FC3)
    
    k=0
    clusters = cv.CreateMat(img.width*img.height, 1, cv.CV_32SC1)
    for i in range(img.height):
        for j in range(img.width):
            s=cv.Scalar(cv.Get2D(img,i,j)[0],cv.Get2D(img,i,j)[1],cv.Get2D(img,i,j)[2])
            cv.Set2D(samples,k,0,s)
            k+=1

    nClusterNum = 2
    cv.KMeans2(samples,nClusterNum,clusters,(cv.CV_TERMCRIT_ITER, 100, 1.0))
    bin=cv.CreateImage((img.width,img.height),cv.IPL_DEPTH_8U,1)

    

    for i in range(img.height):
        for j in range(img.width):
            s=cv.Scalar((clusters.data.i[k++] == 0) ? 255 : 0)
            cv.Set2D(samples,k,0,s)
            k+=1


if __name__=='__main__':
    kmeans()